<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Checkin;
use App\Models\Episode;
use App\Models\Integrate;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;

class CheckingController extends Controller
{
    /***
     *签到列表
     * @param Request $request
     * @param Episode $episode
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request,Checkin $checkin)
    {
            $list=$this->user->checking()->paginate(10)->toArray();
            $list['continue']=$this->user->continue;
        return $this->success('success',$list);
    }


    /***
     *添加签到
     * @param Request $request
     * @param Episode $episode
     * @return \Illuminate\Http\JsonResponse
     */
    public function add(Request $request,Checkin $checkin)
    {
        try {
            DB::beginTransaction();
            $query = $checkin->newQuery();
            $start_time = Carbon::now()->startOfDay()->toDateTimeString();
            $end_time = Carbon::now()->endOfDay()->toDateTimeString();
            if ($query->whereBetween('created_at', [$start_time, $end_time])->exists()) {
                return $this->error('今天已经签过到了');
            }
            $checkin->user_id = $this->user->id;
            $checkin->integral = config("base.shareint");
            if ($this->user->checking()->save($checkin)) {
                if (carbon::parse(now()->toDateString())
                        ->diffInDays(carbon::parse($this->user->continue_time)
                            ->toDateString(), true) > 1) {//断签
                    $this->user->continue = 1;
                } else {//连续签
                    $this->user->continue = $this->user->continue + 1;
                }
                $this->user->continue_time = now()->toDateTimeString();
                if ($this->user->save()) {
                    User::integral($this->user->id, config("base.shareint"), '每日签到', 'CHECKING');
                }
                DB::commit();
                return $this->success('success');
            } else {
                DB::rollBack();
                return $this->error('签到失败');
            }
        }catch (\Exception $exception){
            DB::rollBack();
            return $this->error($exception->getMessage());
        }
    }


}
